/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sda.levelup.lists.linkedlist;

import sda.levelup.lists.IList;


/**
 *
 * @author Дима
 */
public class LinkedListMine implements IList
{

    private Entry header;
    private int size = 0;

    public LinkedListMine() {
        header = new Entry(null);
        header.setNext(header);
        header.setPrev(header);
    }

    public void add(Object value) {
        Entry newEntry = new Entry(value, header, header.getPrev());
        newEntry.getNext().setPrev(newEntry);
        newEntry.getPrev().setNext(newEntry);
        size++;
    }

    private Entry findEntry(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        }
        Entry e = header;
        /*for(int i = 0; i<=index; i++){
         e=e.getNext();
         }*/

        if (index < (size >> 1)) {
            for (int i = 0; i <= index; i++) {
                e = e.getNext();
            }
        }
        else {
            for (int i = size; i > index; i--) {
                e = e.getPrev();
            }
        }
        return e;
    }

    private Entry findEntry(Object o) {
        Entry e = header;
        for (int i = 0; i < size; i++) {
            e = e.getNext();
            if (o.equals(e.getValue())) {
                break;
            }
        }
        if (!header.equals(e)) {
            return e;
        }
        else {
            return null;
        }
    }

    public Object get(int index) {
        return findEntry(index).getValue();
    }

    public void add(int index, Object value) {
        Entry temp = findEntry(index);
        Entry newEntry = new Entry(value, temp, temp.getPrev());
        temp.getPrev().setNext(newEntry);
        temp.setPrev(newEntry);
        size++;
    }

    public int getSize() {
        return size;
    }

    public void remove(int index) {
        Entry temp = findEntry(index);
        temp.getPrev().setNext(temp.getNext());
        temp.getNext().setPrev(temp.getPrev());
        temp.setNext(null);
        temp.setPrev(null);
        size--;
    }

    public void remove(Object o) {
        Entry temp = findEntry(o);
        temp.getPrev().setNext(temp.getNext());
        temp.getNext().setPrev(temp.getPrev());
        temp.setNext(null);
        temp.setPrev(null);
        size--;
    }
    

}
